const mongoose = require('mongoose');
const db = "mongodb://localhost/blog-db"
const glob = require('glob');
const {resolve} = require('path');

mongoose.Promise = global.Promise;

//引入所有的Scheme模型
exports.initSchemas = ()=>{
        glob.sync(resolve(__dirname,'./schema/','**/*.js')).forEach(require);
}

exports.connect = () => {
    //链接数据库
    mongoose.connect(db);
    //链接的最大次数
    let maxConnectTimes = 0;

    return new Promise((resolve, reject) => {

        //当链接断开时，重新连接
        mongoose.connection.on('disconnected', () => {
            //重新连接
            if(maxConnectTimes < 3){
                maxConnectTimes++;
                mongoose.connect();
            }else{
                reject();
                throw new Error('数据库出错!');
            }
        })
        //链接出错时，重新连接
        mongoose.connection.on('error', (err) => {
            if(maxConnectTimes < 3){
                maxConnectTimes++;
                mongoose.connect();
            }else{
                reject();
                throw new Error('数据库出错!');
            };
        })
        //链接打开的时候
        mongoose.connection.once('open', () => {
            resolve();
            console.log('Mongodb Connected successfully!');
        })
    })
}